<template>
  <a-modal
    :visible="visibleValue"
    title="文件详情"
    width="800px"
    :footer="null"
    :destroyOnClose="true"
    @cancel="handleCancel"
  >
    <div class="file-detail-list-container">
      <div v-if="internalFiles && internalFiles.length > 0">
        <div
          v-for="fileItem in internalFiles"
          :key="fileItem.id"
          class="file-list-row"
        >
          <div class="file-info">
            <file-type-icon :fileType="getFileTypeIcon(fileItem)" :size="24" />
            <span class="file-name">{{ fileItem.fileName || '未命名文件' }}</span>
            <span class="file-size" v-if="fileItem.fileSize">{{ formatFileSize(fileItem.fileSize) }}</span>
          </div>
          <div class="file-actions">
            <a-button type="link" size="small" @click="handlePreview(fileItem)">预览</a-button>
            <a-button type="link" size="small" @click="handleDownload(fileItem)">下载</a-button>
            <a-button v-if="!disabled" type="link" size="small" danger @click="handleDelete(fileItem)">删除</a-button>
          </div>
        </div>
      </div>
      <div v-else class="no-files-message">
        没有文件可显示。
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, computed, watch, PropType } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useUserStoreWithOut } from '/@/store/modules/user'; // Assuming this is needed for token
import dayjs from 'dayjs';
import FileTypeIcon from './FileTypeIcon.vue'; // Assuming this component exists and is correct
import { h } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  files: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  fileOrigin: {
    type: String as PropType<'followPlan' | 'followUpContent' | null>,
    default: null,
  },
});

const emit = defineEmits(['update:visible', 'cancel', 'delete', 'preview', 'download']);

const visibleValue = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

// 内部文件列表状态，用于响应式更新
const internalFiles = ref<any[]>([]);

// 监听外部文件列表变化
watch(() => props.files, (newFiles) => {
  internalFiles.value = [...(newFiles || [])];
}, { immediate: true, deep: true });

const userStore = useUserStoreWithOut(); // Initialize userStore

// Methods
function handleCancel() {
  emit('update:visible', false);
  emit('cancel');
}

function handlePreview(fileItem: any) {
  emit('preview', fileItem);
}

function handleDownload(fileItem: any) {
  emit('download', fileItem);
}

function handleDelete(fileItem: any) {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除此文件吗?',
    class: 'delete-confirm-modal',
    icon: h('span', { class: 'warning-icon' }, '!'),
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      // 触发删除事件，让父组件处理删除操作
      emit('delete', fileItem);
      
      // 然后直接从内部文件列表中移除该文件
      internalFiles.value = internalFiles.value.filter(item => item.id !== fileItem.id);
      
      // 如果文件列表为空，自动关闭弹窗
      if (internalFiles.value.length === 0) {
        visibleValue.value = false;
      }
    }
  });
}

function formatFileSize(size: number) {
  if (!size) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let index = 0;
  let fileSize = size;
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }
  return `${fileSize.toFixed(2)} ${units[index]}`;
}

function getFileTypeIcon(file: any) {
  if (!file?.fileName) return 'file';
  const name = file.fileName;
  const ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase();

  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) return 'image';
  if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(ext)) return 'video';
  if (['mp3', 'wav', 'ogg', 'flac', 'aac'].includes(ext)) return 'audio';
  if (ext === 'pdf') return 'pdf';
  if (['doc', 'docx'].includes(ext)) return 'word';
  if (['xls', 'xlsx'].includes(ext)) return 'excel';
  if (['ppt', 'pptx'].includes(ext)) return 'ppt';
  if (['zip', 'rar', '7z'].includes(ext)) return 'archive';
  if (['txt', 'log', 'md'].includes(ext)) return 'text';
  return 'file';
}
</script>

<style lang="less" scoped>
.file-detail-list-container {
  padding: 16px;
  max-height: 70vh;
  overflow-y: auto;
}

.file-list-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .file-info {
    display: flex;
    align-items: center;
    flex-grow: 1;
    margin-right: 16px;

    .file-name {
      margin-left: 8px;
      font-weight: 500;
      color: #333;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .file-size {
      margin-left: 12px;
      color: #999;
      font-size: 12px;
    }
  }

  .file-actions {
    display: flex;
    gap: 8px;

    .ant-btn-link {
      padding: 0 4px;
      height: auto;
      line-height: 1;
    }
  }
}

.no-files-message {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>

<style lang="less">
/* 全局样式，应用于确认弹窗 */
.delete-confirm-modal {
  .ant-modal-content {
    border-radius: 8px;
    overflow: hidden;
  }
  
  .ant-modal-header {
    padding: 16px 24px;
    background-color: #fff;
    border-bottom: none;
  }
  
  .ant-modal-body {
    padding: 0 24px 24px;
  }
  
  .ant-modal-confirm-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
  
  .ant-modal-confirm-content {
    margin-top: 8px;
    margin-left: 28px;
    font-size: 14px;
    color: #333;
  }
  
  .ant-modal-confirm-btns {
    margin-top: 24px;
    
    .ant-btn {
      min-width: 60px;
      height: 32px;
      border-radius: 4px;
    }
    
    .ant-btn-primary {
      background-color: #1890ff;
    }
  }
  
  .warning-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    background-color: #faad14;
    border-radius: 50%;
    color: white;
    font-weight: bold;
    font-size: 14px;
    margin-right: 8px;
    vertical-align: middle;
  }
}
</style>
